Lab - 5: Flutter UI and Frameworks

By Drashya Patel on 2024-12-13T12:06-05:00

Tags: No Tags

Q1: Topic Overview

Definition and Explanation

Changing widgets in response to user input refers to making the behavior of widgets dynamic and adaptable to user actions. Flutter allows developers to update widget states dynamically based on user inputs like taps, swipes, or data changes.

Examples:

  • A button that changes color when clicked.
  • A list that updates when new items are added.

This functionality is crucial for creating responsive and user-friendly applications.


Importance in Mobile Development

  1. Enhances User Experience: Dynamic widgets provide real-time feedback to user actions, ensuring intuitive and engaging interfaces.
  2. Real-Time Updates: Widgets that respond to user inputs allow seamless interactions, such as updating shopping cart contents in an e-commerce app.
  3. Competitive Edge: Applications with responsive UIs stand out in the competitive mobile app market.
  4. Efficient Data Management: Facilitates the integration of complex user flows and data structures without compromising user experience.

Comparison with Related Features

  1. Flutter vs React Native:

    • Flutter uses Dart for declarative UI updates, while React Native relies on JavaScript.
    • Flutter’s single codebase offers seamless cross-platform compatibility, whereas React Native may require platform-specific tweaks.
  2. Flutter vs SwiftUI (iOS):

    • Both support declarative UI updates, but SwiftUI is limited to Apple’s ecosystem, whereas Flutter supports Android and iOS.
  3. Flutter vs Jetpack Compose (Android):

    • Jetpack Compose provides declarative UI updates similar to Flutter but focuses on Android development only.

Advantages and Disadvantages

Advantages:

  1. Improved User Experience: Dynamic updates create interactive and user-friendly interfaces.
  2. Cross-Platform Compatibility: Flutter supports Android and iOS using a single codebase.
  3. Ease of Development: Flutter’s declarative UI system simplifies creating dynamic widgets.

Disadvantages:

  1. Performance Issues: Rebuilding widgets frequently in response to inputs can affect performance in large-scale apps.
  2. Native Feature Limitations: Some native-specific features might require additional configurations.

Q2: Example Implementation

Example 1: Changing Background Color

This example demonstrates a button widget that changes the background color of the app when clicked.

import 'package:flutter/material.dart';

default main() {
  runApp(ColorChangeApp());
}

class ColorChangeApp extends StatefulWidget {
  @override
  _ColorChangeAppState createState() => _ColorChangeAppState();
}

class _ColorChangeAppState extends State<ColorChangeApp> {
  Color backgroundColor = Colors.white;

  void changeColor() {
    setState(() {
      backgroundColor = backgroundColor == Colors.white
          ? Colors.blue
          : Colors.white;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: backgroundColor,
        body: Center(
          child: ElevatedButton(
            onPressed: changeColor,
            child: Text('Change Background Color'),
          ),
        ),
      ),
    );
  }
}

Output:

  1. Initial background: White.
  2. On button press: Background toggles between white and blue.

Example 2: Interactive Slider for Text Size

This example showcases a slider widget that adjusts the size of the displayed text dynamically.

import 'package:flutter/material.dart';

default main() {
  runApp(TextSizeSliderApp());
}

class TextSizeSliderApp extends StatefulWidget {
  @override
  _TextSizeSliderAppState createState() => _TextSizeSliderAppState();
}

class _TextSizeSliderAppState extends State<TextSizeSliderApp> {
  double textSize = 16.0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Text Size Slider')),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Adjustable Text',
              style: TextStyle(fontSize: textSize),
            ),
            Slider(
              min: 10.0,
              max: 50.0,
              value: textSize,
              onChanged: (newSize) {
                setState(() {
                  textSize = newSize;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

Output:

  1. Initial text size: 16.0.
  2. Slider interaction: Dynamically adjusts the text size between 10.0 and 50.0.

Q3: Real-World Scenario

Suggesting Related Products in an E-Commerce App

In an e-commerce application, dynamic widgets can enhance user experience by updating product recommendations in real time based on user interactions. For instance, adding a product to the cart can trigger a widget to display related items.

Code Snippet:

import 'package:flutter/material.dart';

void main() {
  runApp(ECommerceApp());
}

class ECommerceApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Recommended Products')),
        body: RecommendedProductsWidget(),
      ),
    );
  }
}

class RecommendedProductsWidget extends StatefulWidget {
  @override
  _RecommendedProductsWidgetState createState() => _RecommendedProductsWidgetState();
}

class _RecommendedProductsWidgetState extends State<RecommendedProductsWidget> {
  List<String> recommendedProducts = ['Product A', 'Product B', 'Product C'];

  void updateRecommendations(String addedProduct) {
    setState(() {
      recommendedProducts = [
        'Recommended for $addedProduct',
        'Product X',
        'Product Y'
      ];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ElevatedButton(
          onPressed: () => updateRecommendations('Product Z'),
          child: Text('Add Product Z to Cart'),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: recommendedProducts.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(recommendedProducts[index]),
              );
            },
          ),
        ),
      ],
    );
  }
}

Output:

  1. Initially displays generic recommended products.
  2. After adding a product, updates the recommendation list dynamically.